# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django import newforms as forms
from django.contrib.auth.models import User, Group
from django.core import validators
from django.contrib.auth import authenticate, login
from apps.core.models import Udetail

class LoginForm(forms.Form):
    username = forms.CharField(label='user')
    password = forms.CharField(label='pass')
    
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args,  **kwargs)        
        self.fields.get('password').widget = forms.PasswordInput()
        
    def save(self, requestData):
        user = authenticate(
            username = self.cleaned_data.get('username'), 
            password = self.cleaned_data.get('password')
        )
        if user is not None:
            if user.is_active:
                login(requestData, user)
        return user
    
class userBase(forms.Form):
    username = forms.CharField()
    email = forms.EmailField(required=False)
    password = forms.CharField(widget = forms.widgets.PasswordInput)
    utype = forms.ChoiceField(label="Tipo", choices=Udetail.UT)
    
    def clean_username(self):
        try:
            validators.isAlphaNumeric(self.cleaned_data['username'], None)
        except validators.ValidationError, e:
            raise forms.ValidationError(e.messages)
        #if self.cleaned_data['username'] == self.fields['username'].initial:
            #return self.cleaned_data['username']
        try:
            User.objects.get(username__exact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(u'Il nome utente scelto esiste gia\'')
    
    def clean_email(self):
        #if self.cleaned_data['email'] == self.fields['email'].initial:
            #return self.cleaned_data['email']
        try:
            User.objects.get(email__iexact = self.cleaned_data['email'])
        except User.DoesNotExist:
            return self.cleaned_data['email']
        except Exception: pass
        raise forms.ValidationError(u"L'email scelta e' gia' stata usata")
          

class userCreationForm(userBase):    
    password2 = forms.CharField(
        label="Reinserisci la password", widget = forms.widgets.PasswordInput
    )
    def __init__(self, *args, **kwargs):
        super(userCreationForm, self).__init__(*args,  **kwargs)
        self.fields['username'].label = "Inserisci il nome utente:"
        self.fields['password'].label = "Inserisci la password:" 
        self.fields['email'].label = "Inserisci l'e-mail:"
    
    def clean_password2(self):
        if self.cleaned_data['password2'] != self.cleaned_data['password']:
            raise forms.ValidationError("Le password inserite non coincidono")
        else:
            return self.cleaned_data['password2']
            
    def save(self):
        us = User.objects.create_user(self.cleaned_data['username'],  self.cleaned_data['email'],  self.cleaned_data['password'])
        us.save()
        ud = Udetail.Udetail()
        ud.raw_passwd = self.cleaned_data['password']
        ud.user = us
        ud.user_type = self.cleaned_data['utype']
        ud.save()
        return ud

class userForm(userBase):
    first_name = forms.CharField(required=False)
    last_name = forms.CharField(required=False)
    is_active = forms.BooleanField(label="Attivo", required=False)
    is_staff = forms.BooleanField(label="Privilegi di Staff", required=False)
    is_superuser = forms.BooleanField(label="Privilegi di superutente", required=False)
    web_site = forms.URLField(label="Pagina Web", required=False)
    groupAdd = forms.MultipleChoiceField(label='Gruppi da Aggiungere', required=False)
    groupRemove = forms.MultipleChoiceField(label='Gruppi da Rimuovere', required=False)
    address = forms.CharField(label="Indirizzo", required=False)
    city = forms.CharField(label="Citt&agrave di residenza", required=False)
    prov = forms.CharField(label="Provincia", max_length=2, min_length=2, required=False)
    cap = forms.CharField(label="CAP", required=False)
    company = forms.CharField(label="Azienda", required=False)
    tel = forms.CharField(label="Telefono")
    fax = forms.CharField(label="Fax", required=False)
    piva = forms.CharField(label = "Partita IVA", required=False)    
    def __init__(self, oldusername, *args, **kwargs):
        self.oldusername = oldusername
        super(userForm, self).__init__(*args,  **kwargs)
        self.fields['username'].label = "Nome utente:"
        self.fields['password'].label = "Password:" 
        self.fields['email'].label = "Indirizzo e-mail:"
        self.fields['password'].required = False
        if self.oldusername:
            us = User.objects.get(username=self.oldusername)
            self.base_fields['groupAdd'].choices = [ (e.id , e.name) for e in Group.objects.exclude(id__in= [x.id for x in us.groups.all()])]
            self.base_fields['groupRemove'].choices = [(x.id, x.name) for x in us.groups.all()]
    
    def clean_username(self):
        if not self.oldusername or self.cleaned_data['username'] == self.oldusername:
            return self.cleaned_data['username']
        else:
            return super(userForm, self).clean_username()

    def clean_email(self):
        try:
            e = User.objects.get(username=self.oldusername).email
        except:
            e = None
        if e == self.cleaned_data['email']:
            return self.cleaned_data['email']
        else:
            return super(userForm, self).clean_email()
            

    def save(self):
        u = User.objects.filter(username = self.oldusername)
        if u:
            if self.cleaned_data['password']:
                u[0].set_password(self.cleaned_data['password'])
            u[0].email = self.cleaned_data['email']
            u[0].first_name = self.cleaned_data['first_name']
            u[0].last_name = self.cleaned_data['last_name']
            try:
                u[0].username = self.cleaned_data['username']
                u[0].is_active = self.cleaned_data['is_active']
                u[0].is_staff = self.cleaned_data['is_staff']
                u[0].is_superuser = self.cleaned_data['is_superuser']
            except:
                pass
            u[0].save()
            try:
                for g in self.cleaned_data['groupAdd']:
                    u[0].groups.add(g)
                for g in self.cleaned_data['groupRemove']:
                    u[0].groups.remove(g)
            except:
                pass
                
        ud = Udetail.Udetail.objects.filter(user = u[0].id)
        if not ud:
            ud = Udetail.Udetail()
            ud.user = u[0]
        else:
            ud = ud[0]
        ud.raw_passwd = self.cleaned_data['password']
        ud.website = self.cleaned_data['web_site']
        try:
            ud.user_type = self.cleaned_data['utype']
        except:
            pass
        ud.address = self.cleaned_data["address"]
        ud.city = self.cleaned_data["city"]
        ud.prov = self.cleaned_data["prov"]
        ud.cap = self.cleaned_data["cap"]
        ud.company = self.cleaned_data["company"]
        ud.tel = self.cleaned_data["tel"]
        ud.fax = self.cleaned_data["fax"]
        ud.piva = self.cleaned_data["piva"]
        ud.save()

class userFormFe(userForm):
    def __init__(self, *args, **kwargs):
        super(userFormFe, self).__init__(*args,  **kwargs)
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        self.fields['email'].required = True
        self.fields['city'].required = True
        self.fields['prov'].required = True
        self.fields['tel'].required = True
        del self.fields['username']
        del self.fields['groupAdd']
        del self.fields['groupRemove']
        del self.fields['is_active']
        del self.fields['is_staff']
        del self.fields['is_superuser']
        del self.fields['utype']


        
class BaseRegistrationForm(userCreationForm):
    # User Base
    first_name = forms.CharField(label="Nome")
    last_name = forms.CharField(label="Cognome")
    utype = forms.CharField(initial="clients")
    # Udetails
    address = forms.CharField(label="Indirizzo", required=False)
    city = forms.CharField(label="Citt&agrave di residenza", required=False)
    prov = forms.CharField(label="Provincia", max_length=2, min_length=2, required=False)
    #cap = forms.CharField(label="CAP", required=False)
    company = forms.CharField(label="Azienda", required=False)
    tel = forms.CharField(label="Telefono")
    fax = forms.CharField(label="Fax", required=False)
    website = forms.CharField(label="WebSite", initial="http://", required=False)
    #piva = forms.CharField(label = "Partita IVA", required=False)
    contract = forms.BooleanField()
    note = forms.CharField(required=False)
    privacy = forms.BooleanField()
    tiposervizio = forms.CharField()
    note = forms.CharField(required=False)
    
    def __init__(self, *args, **kwargs):
        self.base_fields['note'].widget=forms.widgets.Textarea()
        self.base_fields['tiposervizio'].widget=forms.widgets.RadioSelect()        
        self.base_fields['utype'].widget=forms.widgets.HiddenInput()
        super(BaseRegistrationForm, self).__init__(*args, **kwargs)
    
    def clean_privacy(self):
        if self.cleaned_data['privacy']:
            return self.cleaned_data['privacy']
        else:
            raise forms.ValidationError("E' necessario accettare la normativa sulla privacy")
    
    def clean_contract(self):
        if self.cleaned_data['contract']:
            return self.cleaned_data['contract']
        else:
            raise forms.ValidationError("E' necessario accettare i termini del contratto")  
        
    def save(self):
        try:
            # precompiling the model
            ud = super(BaseRegistrationForm, self).save()
            # saving remaining base user data
            ud.user.is_active = 1
            ud.user.first_name = self.cleaned_data.get('first_name')
            ud.user.last_name = self.cleaned_data.get('last_name')
            ud.user.save()
            # saving remaining user details
            ud.address = self.cleaned_data.get('address')
            ud.city = self.cleaned_data.get('city')
            ud.prov = self.cleaned_data.get('prov')
            #try: 
            #    ud.cap = int(self.cleaned_data.get('cap'))
            #except ValueError, e: 
            ud.cap = 0
            ud.company = self.cleaned_data.get('company')
            ud.tel = self.cleaned_data.get('tel')
            ud.fax = self.cleaned_data.get('fax')
            ud.website = self.cleaned_data.get('website')
            ud.piva = self.cleaned_data.get('piva')
            ud.target_type = self.cleaned_data.get('tiposervizio')
            ud.note = ""
            ud.save()
        except Exception, e:
            print "####--->", e
            
        # sending a confirmation mail...
        try: 
            from libs.utils import mails
            mails.getMailNotification(self.cleaned_data)
        except Exception, e: print e
        return
